package cnki.kg.algorithm;

import org.junit.jupiter.api.Test;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

public class FindMedianSortedArrays {

    @Test
    public void  test(){
        int[] nums1={1,2,3};
        int[] nums2={3,4,5};
        int[] nums3={1,2,3,4,5};
        int[] nums4={3,4,5,6};
        //double res=findMedianSortedArrays(nums1,nums2);
        double res2=findMedianSortedArrays(nums3,nums4);
       // System.out.println(res);
        System.out.println(res2);
    }
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = 0;
        int len2 = 0;
        if (nums1 != null) {
            len1 = nums1.length;
        }
        if (nums2 != null) {
            len2 = nums2.length;
        }
        if (len1 == 0 && len2 == 0) {
            return 0;
        }
        if (len2 > 0 && len1 == 0) {
            int mid = len2 / 2;
            int x = len2 % 2;
            return x > 0 ? nums2[mid] : (nums2[mid] + nums2[mid - 1]) / 2;
        }
        if (len1 > 0 && len2 == 0) {
            int mid = len1 / 2;
            int x = len1 % 2;
            return x > 0 ? nums1[mid] : (nums1[mid] + nums1[mid - 1]) / 2;
        }
        int[] nums = new int[len1 + len2];
        int index = 0;
        int i = 0, j = 0;
        while (index < (len1 + len2)) {
            if (i == len1) {
                while (j != len2) {
                    nums[index] = nums2[j];
                    index++;
                    j++;
                }
                break;
            }
            if (j == len2) {
                while (i != len1) {
                    nums[index] = nums1[i];
                    index++;
                    i++;
                }
                break;
            }

            if (nums1[i] < nums2[j]) {
                nums[index] = nums1[i];
                index++;
                i++;
            } else {
                nums[index] = nums2[j];
                index++;
                j++;
            }
        }
        if (index % 2 == 0) {
            return (nums[index / 2 - 1] + nums[index / 2]) / 2.0;
        } else {
            return nums[index / 2];
        }
    }
}
